<template>
  <div>
    <!-- modal -->
    <div class="modal" v-show="isShow">
      <van-icon name="friends" color="#ffffff" />
      <div class="bg">
        <span class="title">授权登录</span>
        <div class="group">
          <span class="labels">授权码:</span>
          <input
            type="password"
            class="my-input"
            v-model="inputValue"
            placeholder="请输入授权码"
          />
          <van-button
            style="padding:0 20px;border-radius:5px;"
            type="default"
            size="small"
            color="#9999ff"
            :loading="isLoading"
            @click="handleLogin"
            >登录</van-button
          >
        </div>
      </div>
    </div>
    <div class="demo" v-show="!isShow">
      <!-- left-arrow @click-left="onClickLeft" -->
      <van-nav-bar title="数据统计详情" />
      <!-- 开始日期 -->
      <div class="header">
        <div class="example">
          <span>开始日期：</span>
          <input
            readonly
            @click="handleOpenOne"
            v-model="value"
            class="input"
          />
          <!--  dayjs()
                  .subtract(1, 'day')
                  .format('YYYY/M/D') -->
          <mobile-datepicker
            name="dp1"
            :show-picker-model="showDatePicker1"
            :default-date="new Date(currentDate)"
            @cancel="handleCancel"
            @confirm="handleConfirm"
            :endDate="
              new Date(
                curDate2
                  ? dayjs(curDate2).format('YYYY/M/D')
                  : dayjs().format('YYYY/M/D')
              )
            "
          />
        </div>
        <div class="example">
          <span>截至日期：</span>
          <input
            readonly
            @click="showDatePicker2 = true"
            v-model="value2"
            class="input"
          />
          <!-- currentDate2 -->
          <!-- startDate1 -->
          <mobile-datepicker
            name="dp2"
            :show-picker-model="showDatePicker2"
            :default-date="new Date(currentDate2)"
            @cancel="handleCancel2"
            @confirm="handleConfirm2"
            :startDate="
              new Date(
                curDate1
                  ? dayjs(curDate1).format('YYYY/M/D')
                  : dayjs().format('YYYY/M/D')
              )
            "
            :endDate="new Date(endDate2)"
          />
        </div>
      </div>
      <!-- titles -->
      <div class="titles">
        <div class="items">
          <span class="title">预估收益</span>
          <span class="count">{{ (totalIncome / 100000000).toFixed(2) }}</span>
          <span>万元</span>
        </div>
        <div class="items">
          <span class="title">活动访问</span>
          <span class="count">{{ (totalSlotPv / 10000).toFixed(2) }}</span>
          <span>万次</span>
        </div>
        <div class="items">
          <span class="title">广告点击</span>
          <span class="count">{{ (totalAdvertClick / 10000).toFixed(2) }}</span>
          <span>万次</span>
        </div>
      </div>
      <!-- titles end -->
      <h3 class="charts-title">统计趋势图</h3>
      <!-- <van-loading size="24px">加载图表中...</van-loading> -->
      <div id="myChart" :style="{ width: '100%', height: '400px' }"></div>
      <h3 class="charts-title">收入详细内容</h3>
      <template v-if="!isShow">
        <van-tabs
          color="#9999ff"
          @change="tabChange"
          v-model="active"
          swipeable
          change
        >
          <van-tab title="远媒">
            <div class="my-tabs">
              <span class="items">名称</span>
              <span class="items">预估收入</span>
              <span class="items">活动访问</span>
              <span class="items">广告点击</span>
            </div>
            <div class="my-tabs2" v-for="(items, index) in list" :key="index">
              <span class="items">{{ items.appName || "-" }}</span>
              <span class="items">{{
                (items.expectIncome / 10000).toFixed(2) || "-"
              }}</span>
              <span class="items">{{ items.activityShowPv || "-" }}</span>
              <span class="items">{{ items.advertValidClick }}</span>
            </div>
            <van-empty v-if="list.length === 0" description="暂无数据" />
          </van-tab>
          <van-tab title="推啊">
            <div class="my-tabs">
              <span class="items">名称</span>
              <span class="items">预估收入</span>
              <span class="items">活动访问</span>
              <span class="items">广告点击</span>
            </div>
            <div class="my-tabs2" v-for="(items, index) in list" :key="index">
              <span class="items">{{ items.appName || "-" }}</span>
              <span class="items">{{
                (items.expectIncome / 10000).toFixed(2) || "-"
              }}</span>
              <span class="items">{{ items.activityShowPv || "-" }}</span>
              <span class="items">{{ items.advertValidClick }}</span>
            </div>
            <van-empty v-if="list.length === 0" description="暂无数据" />
          </van-tab>
        </van-tabs>
      </template>
    </div>
  </div>
</template>

<script>
import MobileDatepicker from "./MobileDatepicker.vue";
import dayjs from "dayjs";
const currentDate = `${dayjs()
  .subtract(1, "day")
  .format("YYYY/M/D")}`;

const currentDate2 = `${new Date().getFullYear()}/${new Date().getMonth() +
  1}/${new Date().getDate()}`;

const currentDay = `${new Date().getDate()}`;

const startDate1 = dayjs(currentDate2)
  .subtract(Number(currentDay) - 1, "day")
  .format("YYYY/M/D");

const endDate2 = `${new Date().getFullYear()}/${new Date().getMonth() +
  1}/${new Date().getDate()}`;

// const endDate2 = `${dayjs().format("YYYY-M-D")}`
const startTime = dayjs(currentDate).valueOf();
const endTime = dayjs(currentDate2).valueOf();
import {
  getStatisticsDataVerification,
  getStatisticsDataNearly,
  getStatisticsDataListH5Data,
} from "@/api/api";
import { Notify } from "vant";
export default {
  name: "app",
  components: {
    MobileDatepicker,
  },
  data() {
    return {
      dayjs,
      sms: "",
      isShow: true,
      isLoading: false,
      inputValue: "",
      active: 0,
      currentDate,
      currentDate2,
      endDate2,
      startDate1,
      showDatePicker1: false,
      showDatePicker2: false,
      value: currentDate,
      value2: currentDate2,
      totalAdvertClick: 0, //广告点击
      totalIncome: 0, //预期收入
      totalSlotPv: 0, //活动访问
      /* list: [
        { title: "新疆智连", item2: "20", item3: "20", item4: "20" },
        { title: "中国移动-陕西", item2: "20", item3: "20", item4: "20" },
        { title: "健康山西微服务", item2: "20", item3: "20", item4: "20" },
        { title: "新疆移动", item2: "20", item3: "20", item4: "20" },
      ], */
      list: [],
      incomeArr: [],
      slotPvArr: [],
      advertClickArr: [],
      isSuc: false,
      curDate1: "",
      curDate2: "",
    };
  },
  watch: {
    isShow() {
      this.statisticsDataNearly({ startTime });
      this.statisticsDataListH5Data({});
    },
    curDate1(newVal) {
      const startTime = `${dayjs(newVal).valueOf()}`;
      const cur2 = this.curDate2 || dayjs().format("YYYY/M/D");
      const endTime = `${dayjs(cur2).valueOf()}`;
      const type = this.active + 1;

      this.statisticsDataNearly({ startTime, endTime });
      this.statisticsDataListH5Data({ type, startTime, endTime });
    },
    curDate2(newVal) {
      const curDate1 =
        this.curDate1 ||
        dayjs(dayjs().format("YYYY/M/D"))
          .subtract(7, "day")
          .valueOf();
      const startTime = `${dayjs(curDate1).valueOf()}`;
      const endTime = `${dayjs(newVal).valueOf()}`;
      const type = this.active + 1;

      this.statisticsDataNearly({ startTime, endTime });
      this.statisticsDataListH5Data({ type, startTime, endTime });
    },
  },
  /*  updated() {
    if (this.isShow == false) {
      this.statisticsDataNearly({ startTime, endTime });
    }
  }, */
  computed: {},
  methods: {
    /**
     * @func Tabs切换
     */
    tabChange() {
      const type = this.active + 1;
      const curDate1 =
        this.curDate1 ||
        dayjs()
          .subtract(1, "day")
          .format("YYYY/M/D");
      const curDate2 = this.curDate2 || dayjs().format("YYYY/M/D");
      const startTime = `${dayjs(curDate1).valueOf()}`;
      const endTime = `${dayjs(curDate2).valueOf()}`;
      this.statisticsDataListH5Data({ type, startTime, endTime });
    },
    /**
     * @func 验证码
     */
    async statisticsDataVerification(code) {
      this.isLoading = true;
      try {
        const data = await getStatisticsDataVerification({ code });
        if (data) {
          this.isLoading = false;
          this.isShow = false;
          this.inputValue = "";
          Notify({ type: "primary", message: `授权成功` });
        } else {
          Notify({ type: "danger", message: `请输入正确校验码` });
          this.inputValue = "";
          this.isLoading = false;
        }
      } catch (err) {
        this.isLoading = false;
        this.inputValue = "";
        Notify({ type: "danger", message: err.message });
      }
    },
    /**
     * @func 查询总数与趋势图数据
     */
    async statisticsDataNearly(param) {
      const [err, data] = await getStatisticsDataNearly(param);
      if (!err) {
        const { totalAdvertClick, totalIncome, totalSlotPv } = data;
        const perData = data.perData;
        this.totalAdvertClick = totalAdvertClick;
        this.totalIncome = totalIncome;
        this.totalSlotPv = totalSlotPv;
        const income = [];
        const slotPv = [];
        const advertClick = [];
        const dateTime = [];
        for (let items in perData) {
          this.income = income.push(perData[items].income / 10000);
          this.slotPv = slotPv.push(perData[items].slotPv);
          this.advertClick = advertClick.push(perData[items].advertClick);
          this.dateTime = dateTime.push(
            dayjs(Number(perData[items].dateTime)).format("MM-DD")
          );
        }
        const incomeArr = income.filter(Boolean);
        const slotPvArr = slotPv.filter(Boolean);
        const advertClickArr = advertClick.filter(Boolean);
        this.randerCharts(incomeArr, slotPvArr, advertClickArr, dateTime);
      } else {
        Notify({ type: "danger", message: err });
      }
    },
    /**
     * @func 查询详情数据
     */
    async statisticsDataListH5Data(param) {
      const [err, data] = await getStatisticsDataListH5Data(param);
      if (!err) {
        this.list = data;
      }
    },
    /**
     * @func 返回登录页
     */
    onClickLeft() {
      this.isShow = true;
    },
    /***
     * @func 授权登录
     */
    handleLogin() {
      this.statisticsDataVerification(this.inputValue);
    },
    /**
     * @func 渲染图表
     */
    randerCharts(incomeArr, slotPvArr, advertClickArr, dateTime) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById("myChart"));
      // 绘制图表
      myChart.setOption({
        /*   title: {
          text: "折线图堆叠",
        }, */
        dataZoom: [
          {
            type: "inside",
            throttle: "50",
            minValueSpan: 4,
            start: 0,
            end: 15,
          },
        ],
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: ["预估收入", "活动访问", "广告点击"],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          // data: ["07/26", "07/27", "07/28", "07/29", "07/30", "07/31", "08/01"],
          data: dateTime,
        },
        yAxis: [
          {
            name: "元",
            type: "value",
            position: "left",
          },
          {
            name: "次",
            type: "value",
            position: "right",
          },
        ],
        series: [
          {
            name: "预估收入",
            type: "line",
            // stack: "总量",
            data: incomeArr,
            // data: [120, 132, 101, 134, 90, 230, 210],
            yAxisIndex: 0,
          },
          {
            name: "活动访问",
            type: "line",
            data: slotPvArr,
            // data: [220, 182, 191, 234, 290, 330, 310],
            yAxisIndex: 1,
          },
          {
            name: "广告点击",
            type: "line",
            data: advertClickArr,
            // data: [150, 232, 201, 154, 190, 330, 410],
            yAxisIndex: 1,
          },
        ],
      });
    },
    handleOpenOne() {
      this.showDatePicker1 = true;
    },
    handleCancel() {
      this.showDatePicker1 = false;
    },
    handleCancel2() {
      this.showDatePicker2 = false;
    },
    handleConfirm(item) {
      const replaced = item.replace(/-/g, "/");
      const startArr = replaced.split("/");
      const [START_YEAR, START_MONTH, START_DAY] = startArr;
      const [currentYear, currentMonth, currentDay] = [
        new Date().getFullYear(),
        new Date().getMonth() + 1,
        new Date().getDate(),
      ];
      //选择的月份不等于当前月
      if (START_MONTH != currentMonth || START_YEAR != currentYear) {
        //当前选择和实际月份只差一个月
        /* 	if (currentMonth - START_MONTH == 1) {
					if (START_DAY > currentDay) {
						return this.$Toast.fail('上个月日期不能超过当天日期')
					}
				} */
        this.currentDate = replaced;
        // const endDate = dayjs(item).format('YYYY-M-D')
        /* 	const currentEndDate = dayjs(endDate)
					.subtract(1, 'month')
					.format('YYYY-M-D') */
        // this.currentDate2 = endDate
        // this.value2 = endDate
        // this.curDate2 = endDate
        // this.endDate2 = endDate
        // this.startDate1 = currentEndDate
      } else {
        //处理开始日期选择和当月一致
        const date = dayjs().format("YYYY/M/D");
        this.value2 = date;
        this.curDate2 = date;
        this.currentDate2 = date;
        this.currentDate = replaced;
      }
      //处理好的内容赋值给input框
      this.value = replaced;
      this.showDatePicker1 = false;
      this.curDate1 = replaced;
    },
    handleConfirm2(item) {
      const replaced = item.replace(/-/g, "/");
      /*       const startArr = this.value.split("/");
      const endArr = replaced.split("/");
      const [, START_MONTH, START_DAY] = startArr;
       const [, END_MONTH, END_DAY] = endArr;
            if (START_MONTH === END_MONTH) {
        console.log({ END_DAY, START_DAY });
        if (END_DAY < START_DAY) {
          return this.$Toast.fail("结束日期不能小于开始日期");
        }
      }  */
      this.value2 = replaced;
      this.currentDate2 = replaced;
      this.showDatePicker2 = false;
      this.curDate2 = replaced;
    },
  },
};
</script>
<style lang="scss" scoped>
.my-tabs {
  width: 100%;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding: 0 0.2rem;
  margin: 0.2rem 0;
  .items {
    width: 33.33%;
    text-align: center;
  }
}
.my-tabs2 {
  width: 95%;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding: 0.2rem 0;
  margin: 0.2rem 2.5%;
  border: 1px solid rgba(153, 153, 255, 1);
  .items {
    width: 33.33%;
    text-align: center;
    color: #999999;
  }
}
.content {
  width: 95%;
  height: 1rem;
  border: 1px solid rgba(153, 153, 255, 1);
  box-sizing: border-box;
  margin: 0 2.5%;
  .files {
    font-size: 0.2rem;
    width: 30%;
  }
}
.modal {
  width: 100vw;
  height: 100vh;
  background: rgba(153, 153, 255, 1);
  position: relative;
  left: 0;
  top: 0;
  z-index: 2;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .bg {
    width: 80%;
    height: 3.5rem;
    background: #ffffff;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-top: 0.3rem;
    .title {
      font-size: 0.3rem;
      font-weight: bold;
      margin-bottom: 0.4rem;
    }
    .group {
      width: 100%;
      height: 40px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .labels {
        font-size: 0.2rem;
      }
      .my-input {
        border-radius: 2px;
        font-size: 0.2rem;
        width: 50%;
      }
    }
  }
}

#myChart {
  z-index: 1;
}
#mobile-datepicker {
  z-index: 999;
}
.demo {
  font-size: 12px;
  padding-bottom: 10px;
}
.header {
  width: 100%;
  display: flex;
}
.charts-title {
  color: #9999ff;
  padding: 0.2rem;
}
input {
  font-size: 100%;
  border: 1px solid #ccc;
  width: 100%;
  height: 0.6rem;
  padding-left: 0.24rem;
  font-size: 0.3125rem;
  box-sizing: border-box;
}
.titles {
  width: 100%;
  display: flex;
  .items {
    width: 33.33%;
    height: 106px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    background: rgba(153, 153, 255, 1);
    color: #ffffff;
    border-right: 1px solid #ffffff;
    &:last-child {
      border: none;
    }
    .title {
      font-size: 0.25rem;
    }
    .count {
      font-size: 0.35rem;
      font-weight: bold;
    }
  }
}
.example {
  display: flex;
  align-items: center;
  padding: 1em;
  box-sizing: border-box;
  .input {
    width: 2rem;
    border-radius: 5px;
    cursor: pointer !important;
  }
}

.settings {
  margin: 2em 0;
  border-top: 1px solid #bbb;
  background: #eee;
}

h5 {
  font-size: 100%;
  padding: 0.12rem 0;
}

.form-group {
  margin-bottom: 1em;
}

.form-group label {
  font-size: 80%;
  display: block;
}
</style>
